package com.lyc.tokendemo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    public static final Long JWT_TTL = 60 * 60 * 1000L;
    // 密钥明文
    public static final String JWT_Key = "lyc";

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }


    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }

    public static String createJWT(String id,String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    public static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalkey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        long expMills = nowMillis + ttlMillis;
        Date expDate = new Date(expMills);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)    // 主题  可以是JSON数据
                .setIssuer("lyc")       // 发行者
                .setIssuedAt(now)       // 发行时间
                .signWith(signatureAlgorithm, secretKey)  // 使用HS256对称加密签名算法和密钥
                .setExpiration(expDate);
    }

    public static SecretKey generalkey() {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_Key);
        return new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
    }

    public static Claims paresJWT(String jwt) throws Exception {
        SecretKey secretKey = generalkey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
